package com.dotflat.rest.controller;

import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.AreableObjectBaseService;
import com.starinside.wp.components.MemVerificationCache;
import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.ChildrenService;
import com.starinside.wp.service.WxUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;

//import static com.matt.foundation.constant.RequestConstant.TICKET;

@Slf4j
public class RestfulBaseController<T1, T2 extends AreableObjectBaseService<T1>, P extends AreableObjectBasePO> {

    @Autowired
    protected ChildrenService childrenService;

    @Autowired
    protected BindedBabyService bindedBabyService;

    @Autowired
    protected WxUserService wxUserService;

    protected T2 baseService;
    public void setBaseService(T2 service){
        this.baseService = service;
    }

    @Autowired
    protected MemVerificationCache cache;


    protected String validChildrenId(String childId, HttpServletRequest req){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        List<BindedBabyVO> allbinded = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());

        if (allbinded == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "当前家长没有就读的宝宝");
        }

        if(StringUtils.isEmpty(childId)) {
            if (loginUser.getDefaultBabyId() == null) {
                BindedBabyVO baby = allbinded.get(0);
                childId = baby.getId();

                return childId;
            }else{
                childId = loginUser.getDefaultBabyId();
            }
        }

        String finalChildId = childId;
        List<BindedBabyVO> filtered = allbinded.stream().filter(o->o.getId().equals(finalChildId)).collect(Collectors.toList());
        if (filtered.size() == 0){
            //没有合法的宝宝
            //重置默认宝宝
            BindedBabyVO defaultBaby = allbinded.get(0);
            log.info("setting default baby for user :: " + loginUser.getId() + ":::" + defaultBaby.getId());
            loginUser.setDefaultBabyId(defaultBaby.getId());
            loginUser.setDefaultBaby(defaultBaby);
            wxUserService.save(loginUser);
            //
            childId = loginUser.getDefaultBabyId();
        }

        return childId;
    }

    @ApiOperation(value = "获取列表")
    @GetMapping("/list")
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, HttpServletRequest req, P param, PagerQuery pagerQuery){

        String childId = validChildrenId(null, req);
        Children children = childrenService.getById(childId);

        if (children == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "没有绑定宝宝");
        }

        Sort sort = null;

        Field[] fields = param.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0){
            for (Field f: fields){
                if ("sort".equals(f.getName())){
                    sort = Sort.by("sort", "created").descending();
                    break;
                }
            }
        }
        if (sort == null){
            sort = Sort.by("created").descending();
        }

        PageRequest pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize(), sort);

        return StatusResponse.success( baseService.page(children.getAreaId(), children.getId(), param, pageRequest));
    }

//    @ApiOperation(value = "增加一条记录")
//    @PostMapping()
//    public StatusResponse add(@RequestHeader(TICKET) String ticket, P param){
//        StaffDTO staff = cache.getStaff(ticket);
//
//        T1 ret = baseService.add(staff.getAreaId(), staff.getId(), param);
//
//        List<T1> tmp = new ArrayList<>();
//        tmp.add(ret);
//
//        return StatusResponse.success(tmp);
//    }

    @ApiOperation(value = "获取一个对象")
    @GetMapping()
    public StatusResponse get(@RequestHeader(TICKET) String ticket, HttpServletRequest req, String id){

        String childId = validChildrenId(null, req);
        Children children = childrenService.getById(childId);

        return StatusResponse.success(baseService.get(children.getAreaId(), null, id));
    }

//    @ApiOperation(value = "逻辑删除一个或多个对象")
//    @DeleteMapping()
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
//            @ApiImplicitParam(paramType = "formData", name = "ids", value = "对象id数组", required = false, dataType = "string[]"),
//            @ApiImplicitParam(paramType = "formData", name = "id", value = "对象id， 和ids二选一", required = false, dataType = "string")
//    })
//    public StatusResponse delete(@RequestHeader(TICKET) String ticket, String[] ids, String id ){
//        StaffDTO staff = cache.getStaff(ticket);
//
//        if (StringUtils.isNotEmpty(id)) {
//            AreableObjectBasePO param = new AreableObjectBasePO();
//            param.setId(id);
//
//            baseService.delete(staff.getAreaId(), staff.getId(), param);
//        }else if(ids != null && ids.length > 0){
//            baseService.delete(staff.getAreaId(), staff.getId(), ids);
//        }else{
//            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误!");
//        }
//
//        return StatusResponse.success();
//    }

}
